package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.model.product.SpuSaleAttr;
import com.atguigu.gmall.product.mapper.SpuSaleAttrMapper;
import com.atguigu.gmall.product.service.SpuSaleAttrService;
import com.atguigu.gmall.product.service.SpuSaleAttrValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/***
 * spu销售属性表service层实现类
 */
@Service
public class SpuSaleAttrServiceImpl implements SpuSaleAttrService {

    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuSaleAttrValueService spuSaleAttrValueService;

    /**
     * 保存spu销售属性表数据
     *
     * @param spuInfoId
     * @param spuSaleAttrList
     * @return
     */
    @Override
    public Integer save(Long spuInfoId, List<SpuSaleAttr> spuSaleAttrList) {
        //遍历保存
        spuSaleAttrList.stream().forEach(spuSaleAttr -> {
            //补全spuid
            spuSaleAttr.setSpuId(spuInfoId);
            //新增
            int insert = spuSaleAttrMapper.insert(spuSaleAttr);
            if(insert <= 0) {
                throw new GmallException("新增spu销售属性表数据失败",null);
            }
            //新增spu属性值表数据
            spuSaleAttrValueService.save(spuInfoId,spuSaleAttr.getSpuSaleAttrValueList(),spuSaleAttr.getSaleAttrName());
        });

        //返回结果
        return 1;
    }

    /**
     * 根据spuId查询数据
     *
     * @param spuId
     * @return
     */
    @Override
    public List<SpuSaleAttr> listBySpuId(Long spuId) {
        return spuSaleAttrMapper.selectListBySpuId(spuId);
    }

    /**
     * 根据spuid和skuid查询当前商品所属spu的全部销售属性和值,并且标识当前应该选中哪几个值
     *
     * @param skuId
     * @return
     */
    @Override
    public List<SpuSaleAttr> listSpuSaleAttrBySpuIDAndSkuId(Long spuId,Long skuId) {
        return spuSaleAttrMapper.selectListBySpuIdAndSkuId(spuId,skuId);
    }
}
